<?php
// Codenova.pl
// -------------------------
//
// Project: Jasminum
// Thumbnail: AdminController.php
// Author: Kamil Mrzyglod
//
// ------------------------- 
// Copyright(c) 2013 by Codenova.pl


namespace Modules\JasminumNews\Controllers;

use Gotcha\App\Extensions\GotchaCulturesExtension;
use Gotcha\App\Extensions\GotchaErrorsExtension;
use Gotcha\App\Extensions\GotchaFileSystemExtension;
use Gotcha\App\Extensions\GotchaLogsExtension;
use Gotcha\App\Extensions\HttpExtension;
use Gotcha\App\Framework\Controller;
use Gotcha\App\Types\String;
use GotchaDatabase\GotchaSettingsQuery;
use GotchaDatabase\JasminumNews;
use GotchaDatabase\JasminumNewsLinks;
use GotchaDatabase\JasminumNewsLinksQuery;
use GotchaDatabase\JasminumNewsQuery;

class AdminController extends Controller {
    private $allowedExtensions = array('jpg', 'jpeg', 'png', 'gif');

    public function Index() {
        return parent::View();
    }

    public function Edit() {
        return parent::View();
    }

    public function EditPost() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_POST['Id']) || !isset($_POST['Id'])) {
            die('Error');
        }

        if(empty($_POST['Title']) || empty($_POST['Body'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Edit?error=1&id='.$_POST['Id']));
            exit;
        }

        $menu = JasminumNewsQuery::create()
                    ->findOneById($_POST['Id'])
                        ->getThumbnail();

        // Check if user chose new menu
        if(isset($_FILES['Thumbnail']['name']) && !empty($_FILES['Thumbnail']['name'])) {
            // Check if it's a  new file
            if($menu != $_FILES['Thumbnail']['name']) {
                // Validate file
                if($_FILES['Thumbnail']['error'] != 0) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Edit?error=2&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['Thumbnail']['name'])) {
                    $file = explode('.', $_FILES['Thumbnail']['name']);
                    $fileExtension = end($file);
                    if(!in_array($fileExtension, $this->allowedExtensions)) {
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Edit?error=3&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Edit?error=5&id='.$_POST['Id']));
                    exit;
                }

                if(isset($_FILES['Thumbnail']['size'])) {
                    if($_FILES['Thumbnail']['size'] > 1024000) { // More than 10MB
                        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Edit?error=7&id='.$_POST['Id']));
                        exit;
                    }
                } else {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Edit?error=6&id='.$_POST['Id']));
                    exit;
                }

                // Check file existence
                $settings = GotchaSettingsQuery::create()
                    ->findOneByStrongName('GalleryMainDir');
                $NewsDir = $settings->getValue();

                if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['Thumbnail']['name']), new String(GOTCHA_ROOT_DIR.$NewsDir.DIRECTORY_SEPARATOR.'News'.DIRECTORY_SEPARATOR)) == true) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Edit?error=8&id='.$_POST['Id']));
                    exit;
                }

                // File passed validation, upload it
                move_uploaded_file($_FILES['Thumbnail']['tmp_name'], GOTCHA_ROOT_DIR.$NewsDir.DIRECTORY_SEPARATOR.'News'.DIRECTORY_SEPARATOR.$_FILES['Thumbnail']['name']);
            }
        } else {
            $_FILES['Thumbnail']['name'] = $menu;
        }

        // Update
        try {
            JasminumNewsQuery::create()
                ->findOneById($_POST['Id'])
                ->setTitle($_POST['Title'])
                ->setThumbnail($_FILES['Thumbnail']['name'])
                ->setBody($_POST['Body'])
                ->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        // News links
        if(!empty($_POST['NewsLinks'])) {
            try {
                // Delete old links
                $oldLinks = JasminumNewsLinksQuery::create()
                                ->findByJasminumNewsId($_POST['Id']);
                foreach($oldLinks as $oldLink) {
                    $oldLink->delete();
                }

                // Get last news
                $lastNews = $_POST['Id'];

                $links = explode(';', $_POST['NewsLinks']);
                foreach($links as $link) {
                    if(!empty($link)) {
                        $urlAndName = explode(' ', $link);
                        $linksQuery = new JasminumNewsLinks();
                        $linksQuery->setLink($urlAndName[0]);
                        $linksQuery->setUrl($urlAndName[1]);
                        $linksQuery->setJasminumNewsId($lastNews);
                        $linksQuery->save();
                    }
                }
            } catch(\Exception $e) {
                GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
                GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
                exit;
            }
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News?edit=1'));
        exit;
    }

    public function Create() {
        return parent::View();
    }

    public function CreatePost() {
        $http = new HttpExtension();

        if(empty($_POST['Title']) || empty($_POST['Body'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Create?error=1'));
            exit;
        }

        if(!empty($_FILES['Thumbnail']['name'])) {
            if(isset($_FILES['Thumbnail']['name'])) {
                $fileExtension = end(explode('.', $_FILES['Thumbnail']['name']));
                if(!in_array($fileExtension, $this->allowedExtensions)) {
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Create?error=3'));
                    exit;
                }
            } else {
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Create?error=5'));
                exit;
            }

            if(isset($_FILES['Thumbnail']['size'])) {
                if($_FILES['Thumbnail']['size'] > 1024000) { // More than 10MB
                    header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Create?error=7'));
                    exit;
                }
            } else {
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Create?error=6'));
                exit;
            }

            // Check file existence
            $settings = GotchaSettingsQuery::create()
                ->findOneByStrongName('GalleryMainDir');
            $thumbnailsDir = $settings->getValue();

            if(GotchaFileSystemExtension::CheckFileExistence(new String($_FILES['Thumbnail']['name']), new String(GOTCHA_ROOT_DIR.$thumbnailsDir.DIRECTORY_SEPARATOR.'News'.DIRECTORY_SEPARATOR)) == true) {
                header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News/Create?error=8'));
                exit;
            }

            // File passed validation, upload it
            move_uploaded_file($_FILES['Thumbnail']['tmp_name'], GOTCHA_ROOT_DIR.$thumbnailsDir.DIRECTORY_SEPARATOR.'News'.DIRECTORY_SEPARATOR.$_FILES['Thumbnail']['name']);
        }

        // Add new menu
        try {
            $news = new JasminumNews();
            $news->setTitle($_POST['Title']);
            $news->setThumbnail($_FILES['Thumbnail']['name']);
            $news->setBody($_POST['Body']);
            $news->setGotchaUsersId(1);

            // Set date
            $date = new \DateTime();

            $news->setCreationDate($date->format('Y-m-d'));
            $news->setCreationTime($date->format('H:i:s'));

            $news->save();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        // News links
        if(!empty($_POST['NewsLinks'])) {
            try {
                // Get last news
                $lastNews = JasminumNewsQuery::create()
                    ->orderById('desc')
                    ->findOne();

                $links = explode(';', $_POST['NewsLinks']);
                foreach($links as $link) {
                    if(!empty($link)) {
                        $urlAndName = explode(' ', $link);
                        $linksQuery = new JasminumNewsLinks();
                        $linksQuery->setLink($urlAndName[0]);
                        $linksQuery->setUrl($urlAndName[1]);
                        $linksQuery->setJasminumNewsId($lastNews->getId());
                        $linksQuery->save();
                    }
                }
            } catch(\Exception $e) {
                GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
                GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
                exit;
            }
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News?create=1'));
        exit;
    }

    public function CreateLink() {
        return parent::View();
    }

    public function EditLink() {
        return parent::View();
    }

    public function Delete() {
        $http = new HttpExtension();

        // Validate input
        if(empty($_GET['id'])) {
            header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News?error=2'));
            exit;
        }

        // Delete element
        try {
            JasminumNewsQuery::create()->findOneById($_GET['id'])->delete();
        } catch (\Exception $e) {
            GotchaLogsExtension::createNewLogEntry(new String($e->getMessage()));
            GotchaErrorsExtension::throwError(new String(GotchaCulturesExtension::getTranslation(new String('ERROR_DURING_EXECUTING_QUERY'))));
            exit;
        }

        header('Location: '.$http->resolveAbsoluteUrl().parent::UrlContent('/Admin/Jasminum/News?delete=1'));
        exit;
    }

    public function returnNews() {
        $news = JasminumNewsQuery::create()
            ->orderById()
            ->find();

        // HTML cache
        $html = '';
        foreach($news as $onenews) {
            $html .= '<tr>';
            $html .= sprintf('<td>%s</td><td>%s</td><td>[ <a href="%s?id=%s">Edytuj</a> | <a href="%s?id=%s" class="delete">Usuń</a> ]</td>', $onenews->getTitle(), $onenews->getCreationDate().' '.$onenews->getCreationTime(), parent::UrlContent('/Admin/Jasminum/News/Edit'), $onenews->getId(), parent::UrlContent('/Admin/Jasminum/News/Delete'), $onenews->getId());
            $html .= '</tr>';
        }

        if($news->count() == 0) {
            $html .= '<tr><td colspan="8">Nie ma dodanych rezerwacji.</td></tr>';
        }

        return $html;
    }

    public function returnOneNews($id) {
        $news = JasminumNewsQuery::create()
            ->findOneById($id);
        return $news;
    }

    public function returnLinks($id) {
        $links = JasminumNewsLinksQuery::create()
                    ->findByJasminumNewsId($id);

        $html = '';
        foreach($links as $link) {
            $html .= $link->getUrl().' '.$link->getLink().';';
        }
        return $html;

    }
}